package com.zjy.software.day16;

import java.io.*;
import java.util.Arrays;

public class FileStreamDemo {
    public static void main(String[] args) throws IOException {

//        fileInputReadDemo();
//        fileInputReadArrayDemo();
//        testFileOutputStremDemo();
        testCopyFileDemo();
    }

    private static void fileInputReadDemo() throws IOException {
        File file=new File("newfile.txt");

        FileInputStream fileInputStream=new FileInputStream(file);
        int read = fileInputStream.read();
        System.out.println("read = " + read);
        int read1 = fileInputStream.read();
        System.out.println("read1 = " + read1);


        System.out.println("read = " + read);
        System.out.println("(char)read = " + (char)read);
        while (read!=-1){
            read = fileInputStream.read();
            System.out.println("read = " + (char)read);
        }

        //使用完成流以后一定要关闭,否则会造成内存泄漏
        fileInputStream.close();
    }
    private static void fileInputReadArrayDemo() throws IOException {
        File file=new File("newfile.txt");

        byte[] bytes=new byte[10];
        FileInputStream fileInputStream=new FileInputStream(file);
//        int read = fileInputStream.read(bytes);
//        String string = Arrays.toString(bytes);
//        System.out.println("string = " + string);

        int i =0;
        while ((i = fileInputStream.read( bytes ))!=-1) {
//            System.out.println( "charArray = " + Arrays.toString(bytes));
             String string = new String( bytes, 0, i );
            System.out.println( "string = " + string );
        }

        //使用完成流以后一定要关闭,否则会造成内存泄漏
        fileInputStream.close();
    }

    private static void testFileOutputStremDemo() throws IOException {
        File file=new File("out.txt");
        FileOutputStream fileOutputStream=new FileOutputStream(file);
        fileOutputStream.write(99);
        fileOutputStream.write("hello兰州".getBytes());
        fileOutputStream.write("welcome".getBytes(),2,2);
        fileOutputStream.flush();
        fileOutputStream.close();
    }
    
    private static void testCopyFileDemo() throws IOException {
        File file = new File("out.txt");
        File file1 = new File("test1.txt");
        FileInputStream fileInputStream = new FileInputStream(file);
        FileOutputStream fileOutStream = new FileOutputStream(file1);
        int i = 0;

//     字符数组读入
        byte[] byteArray = new byte[100];

        while ((i = fileInputStream.read(byteArray)) != -1) {
            String string = new String(byteArray, 0, i);
            System.out.println("string = " + string);
            fileOutStream.write(byteArray, 0, i);
        }
        fileInputStream.close();
        fileOutStream.close();

    }
    }
